function DateDifference(faultDate, completeTime) {
  // let d1 = new Date(faultDate);
  // let d2 = new Date(completeTime);
  var stime = new Date(faultDate).getTime();
  var etime = new Date(completeTime).getTime();
  var usedTime = etime - stime; //两个时间戳相差的毫秒数
  var days = Math.floor(usedTime / (24 * 3600 * 1000));
  //计算出小时数
  var leave1 = usedTime % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
  var hours = Math.floor(leave1 / (3600 * 1000));
  //计算相差分钟数
  var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
  var minutes = Math.floor(leave2 / (60 * 1000));
  var time = days + "天" + hours + "时" + minutes + "分";
  // var time = days;
  return time;
}

layui.define(["table", "form", "upload", "admin"], function (exports) {
  var $ = layui.$,
    table = layui.table,
    form = layui.form,
    upload = layui.upload,
    admin = layui.admin;
  table.on("sort(LAY-user-manage)", function (obj) {
    //尽管我们的 table 自带排序功能，但并没有请求服务端。
    //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
    table.reload("LAY-user-manage", {
      initSort: obj, //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
      where: {
        //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
        field: obj.field, //排序字段   在接口作为参数字段  field order
        order: obj.type, //排序方式   在接口作为参数字段  field order
      },
      parseData: function (res) {
        // 这个地方加这个是因为 直接排序会错乱有问题，排序不准，
        $.each(res.data, function (i, key, value) {
          res.data[i].diamond = parseFloat(res.data[i].diamond);
          res.data[i].gold = parseFloat(res.data[i].gold);
          res.data[i].point = parseFloat(res.data[i].point);
        });
      },
    });
  });
  //
  table.render({
    elem: "#LAY-user-manage",
    url: "/admin/user/getlist",
    where: { reg_source_id: $("#regSourceId").val() },
    initSort: {
      field: "regist_time", //排序字段，对应 cols 设定的各字段名
      type: "desc", //排序方式  asc: 升序、desc: 降序、null: 默认排序
    },
    sort: true, //重点1：这里的sort表示 table表在取得接口数据后，对页面渲染后的table数据进行排序。同时，这里的true 会影响页面sort 上下小箭头的 显示效果
    cols: [
      [
        {
          field: "mobile",
          width: 105,
          title: "手机号",
          sort: true,
          fixed: "left",
        },
        { field: "id", width: 100, title: "用户ID", sort: true, fixed: "left" },
        {
          field: "account",
          width: 100,
          title: "账号",
          sort: true,
          fixed: "left",
        },
        {
          field: "nick_name",
          title: "昵称",
          minWidth: 120,
          templet: function (d) {
            return decodeURI(d.nick_name);
          },
        },
        {
          field: "",
          title: "头像",
          width: 80,
          templet: function (d) {
            if (d.avatar) {
              return (
                '<img style="display: block;margin:0px auto; height: 100%;" src= "' +
                d.avatar +
                '">'
              );
            } else {
              return "无";
            }
          },
        },
        {
          field: "",
          title: "帐号状态",
          width: 100,
          templet: function (d) {
            if (d.status == 0) {
              return '<span class="layui-badge layui-bg-green">正常</span>';
            }
            if (d.status == 1) {
              return '<span class="layui-badge layui-bg-danger">封禁</span>';
            }
            if (d.status == 2) {
              return '<span class="layui-badge layui-bg-warning">暂时冻结</span>';
            }
            if (d.status == 3) {
              return '<span class="layui-badge layui-bg-warning">被踢出</span>';
            }
            if (d.status == 4) {
              return '<span class="layui-badge layui-bg-warning">销户</span>';
            }
          },
        },
        {
          field: "",
          title: "是否贵族",
          width: 95,
          align: "center",
          templet: function (d) {
            if (d.noble && d.noble.length > 0) {
              return "是";
            }

            return "否";
          },
        },
        {
          field: "",
          title: "贵族归属ID",
          width: 115,
          align: "center",
          templet: function (d) {
            if (d.noble && d.noble.length > 0) {
              if (d.noble[0].anchor_id == 0 && d.noble[0].from == 1) {
                return "官方";
              }

              if (d.noble[0].anchor_id) {
                return d.noble[0].anchor_id;
              }
            }

            return "无";
          },
        },
        { field: "diamond", width: 120, title: "龙钻数量", sort: true },
        { field: "gold", width: 120, title: "金币数量", sort: true },
        { field: "point", width: 100, title: "经验值", sort: true },
        // {field: "anchor_point", width: 100, title: "主播经验值"},
        {
          field: "",
          width: 100,
          title: "在线状态",
          templet: function (d) {
            switch (d.online_status) {
              case 1:
                return '<span class="layui-badge layui-bg-green">在线</span>';
              case 2:
                return '<span class="layui-badge layui-bg-orange">暂离</span>';
              case 3:
                return '<span class="layui-badge layui-bg-red">通话中</span>';
              case 9:
                return '<span class="layui-badge layui-bg-black">离线</span>';
              default:
                return '<span class="layui-badge layui-bg-gray">离线</span>';
            }
          },
        },
        {
          field: "",
          width: 100,
          title: "渠道来源",
          templet: function (d) {
            return d.regsource ? d.regsource.source_name : "官方";
          },
        },
        { field: "last_login", title: "最后一次登录时间", width: 180 },
        {
          field: "last_ip",
          title: "最后登录IP",
          width: 150,
          align: "center",
          templet: function (d) {
            if (d.last_ip) {
              return d.last_ip;
            }

            return "-";
          },
        },
        {
          field: "",
          width: 100,
          title: "登录设备",
          templet: function (d) {
            switch (d.login_platform) {
              case 0:
                return '<span class="layui-badge layui-bg-red">WEB</span>';
              case 1:
                return '<span class="layui-badge layui-bg-blue">IOS</span>';
              case 2:
                return '<span class="layui-badge layui-bg-green">Android</span>';
              case 3:
                return '<span class="layui-badge layui-bg-green">H5</span>';
              default:
                return " 未知";
            }
          },
        },
        { field: "device_info", title: "注册设备ID", width: 200 },
        { field: "regist_time", title: "注册时间", sort: true, width: 180 },
        { field: "regist_ip", title: "注册IP", width: 150 },
        {
          field: "",
          title: "注册来源",
          width: 130,
          templet: function (d) {
            //注册来源 0 后台 1 WEB 2 IOS 3 Android.
            switch (d.regist_type) {
              case 0:
                return '<span class="layui-badge layui-bg-gray">后台</span>';
              case 1:
                return '<span class="layui-badge layui-bg-red">WEB</span>';
              case 2:
                return '<span class="layui-badge layui-bg-blue">IOS</span>';
              case 3:
                return '<span class="layui-badge layui-bg-green">Android</span>';
              case 4:
                return '<span class="layui-badge layui-bg-green">H5</span>';

              default:
                return " 未知旧数据 ";
            }
          },
        },
        {
          field: "",
          title: "来源直播间",
          align: "center",
          width: 130,
          templet: function (d) {
            if (d.recommend && d.recommend.origin_anchor_id) {
              return d.recommend.origin_anchor_id;
            }

            return "无";
          },
        },
        { field: "regist_area", title: "所属地区", width: 150 },
        {
          field: "",
          width: 150,
          title: "账号类型",
          templet: function (d) {
            switch (d.is_anchor) {
              case 0:
                if (d.anchor_type == 3) {
                  return '<span class="layui-badge layui-bg-orange">测试用户</span>';
                }
                return '<span class="layui-badge layui-bg-orange">用户</span>';
            }
            var html = "";

            switch (d.anchor_type) {
              case 1:
                html = '<span class="layui-badge layui-bg-green">主播</span>';
                break;
              case 2:
                html = '<span class="layui-badge layui-bg-red">公司主播</span>';
                break;
              case 3:
                html = '<span class="layui-badge layui-bg-red">测试主播</span>';
                break;
            }

            return html;
          },
        },
        {
          field: "",
          width: 150,
          title: "专家角色",
          templet: function (d) {
            var expert_html = "-";
            switch (d.expert_type) {
              case 1:
                expert_html =
                  '<span style="margin-left:5px;" class="layui-badge layui-bg-red">专家</span>';
                break;
              case 2:
                expert_html =
                  '<span style="margin-left:5px;" class="layui-badge layui-bg-black">测试专家</span>';
                break;
            }
            return expert_html;
          },
        },

        {
          field: "",
          title: "禁言时间",
          width: 180,
          templet: function (d) {
            if (d.bannerd_user != null) {
              if (
                d.bannerd_user.ban_time === 0 ||
                d.bannerd_user.ban_time >= 4294967295
              ) {
                return "永久禁言";
              }
              return DateDifference(
                new Date().getTime(),
                d.bannerd_user.ban_time * 1000
              );
            }
            return "";
          },
        },
        {
          field: "checkin_continuous",
          title: "连续签到",
          width: 120,
          sort: true,
          templet: function (d) {
            return d.checkin_continuous > 0 ? d.checkin_continuous : 0;
          },
        },
        {
          field: "checkin_count",
          title: "累计签到",
          width: 120,
          sort: true,
          templet: function (d) {
            return d.checkin_count > 0 ? d.checkin_count : 0;
          },
        },
        {
          field: "banned_num",
          title: "封禁次数",
          width: 100,
          templet: function (d) {
            return d.banned_num + "次";
          },
        },
        {
          title: "操作",
          width: 500,
          align: "right",
          fixed: "right",
          toolbar: "#table-userlist-operation",
        },
      ],
    ],
    page: true,
    limit: 20,
    height: "full-180",
    text: "对不起，加载出现异常！",
    even: true,
  });

  //监听工具条
  table.on("tool(LAY-user-manage)", function (obj) {
    if (obj.event === "del") {
      if (obj.data.status == 5) {
        return layer.msg("注销状态的用户不可操作", { icon: 5 });
      }
      var status = 1;
      var confirm_str = "确定封禁用户吗？";
      switch (obj.data.status) {
        case 0:
          status = 1;
          break;
        default:
          status = 0;
          confirm_str = "确定解封用户吗？";
          break;
      }

      layer.confirm(confirm_str, function (index) {
        layer.load();
        admin.req({
          url: "/admin/user/del_post",
          data: { id: obj.data.id, status: status },
          success(res) {
            layer.closeAll("loading");
            if (res.code == 0) {
              table.reload("LAY-user-manage");
              layer.msg(res.msg, { icon: 1 });
            }
          },
          complete: function (res) {
            layer.closeAll("loading");
          },
        });
      });
    } else if (obj.event === "edit") {
      var index = layer.open({
        type: 2,
        title: "编辑用户",
        content: "/admin/user/edit?id=" + obj.data.id,
        maxmin: true,
        area: ["800px", "460px"],
      });
      layer.full(index);
    } else if (obj.event === "viewBehavior") {
      layer.open({
        type: 2,
        title: "用户查看",
        content: "/admin/user/backpack?uid=" + obj.data.id,
        maxmin: true,
        area: ["1300px", "700px"],
      });
    } else if (obj.event == "setAdmin") {
      // layer.confirm('确定将改用户设为房间管理？', function (index) {
      //     admin.req({
      //         url: '/admin/user/setAdmin'
      //         , data: {"id": obj.data.id}
      //         , success(res) {
      //             if (res.code == 0) {
      //                 table.reload("LAY-user-manage");
      //                 layer.msg(res.msg, {icon: 1});
      //             } else {
      //                 layer.msg(res.msg, {icon: 5});
      //             }
      //         }
      //     });
      // });
      layer.open({
        type: 2,
        title: "确定将改用户设为房间管理",
        content: "/admin/user/setAdminShow?id=" + obj.data.id,
        maxmin: true,
        area: ["500px", "450px"],
      });
    } else if (obj.event == "delAdmin") {
      layer.msg("请到房间管理员列表页面取消管理身份", { icon: 5 });
    } else if (obj.event == "bannerd") {
      layer.open({
        type: 2,
        title: "确定禁言该用户吗?",
        content: "/admin/user/setBanTime?id=" + obj.data.id,
        maxmin: true,
        area: ["700px", "530px"],
      });
      // layer.confirm('确定禁言该用户吗?', function (index) {
      //     admin.req({
      //         url: '/admin/user/setBanned'
      //         , data: {"id": obj.data.id}
      //         , success(res) {
      //             if (res.code == 0) {
      //                 table.reload("LAY-user-manage");
      //                 layer.msg(res.msg, {icon: 1});
      //             } else {
      //                 layer.msg(res.msg, {icon: 5});
      //             }
      //         }
      //     });
      // });
    } else if (obj.event == "unbannerd") {
      layer.confirm("确定解除禁言？", function (index) {
        layer.load();
        admin.req({
          url: "/admin/user/unBanned",
          data: { id: obj.data.bannerd_user.id },
          success(res) {
            if (res.code == 0) {
              table.reload("LAY-user-manage");
              layer.msg(res.msg, { icon: 1 });
            }
          },
          complete: function (res) {
            layer.closeAll("loading");
          },
        });
      });
      // layer.msg("请到禁言列表页面解除禁言", { icon: 5 });
    } else if (obj.event == "remove_device_blacklist") {
      layer.confirm("确定要移除设备黑名单吗？", function (index) {
        admin.req({
          url: "/admin/user/device_blacklist",
          data: { id: obj.data.id, status: 2 },
          success(res) {
            if (res.code == 0) {
              layer.msg(res.msg, { icon: 1 }, function () {
                window.location.reload();
              });
            } else {
              layer.msg(data.msg, { icon: 2 });
            }
          },
        });
      });
    } else if (obj.event == "device_blacklist") {
      layer.confirm("确定要拉黑设备吗？", function (index) {
        admin.req({
          url: "/admin/user/device_blacklist",
          data: { id: obj.data.id, status: 1 },
          success(res) {
            if (res.code == 0) {
              layer.msg(res.msg, { icon: 1 }, function () {
                window.location.reload();
              });
            } else {
              layer.msg(data.msg, { icon: 2 });
            }
          },
        });
      });
    }
  });

  form.on("submit(user-add)", function (obj) {
    var data = obj.field;
    layer.load();
    //提交
    admin.req({
      url: "/admin/user/add_post",
      data: data,
      success: function (res) {
        layer.closeAll("loading");
        if (res.code == 0) {
          layer.msg(res.msg, { icon: 1 });
          setTimeout(function () {
            window.location.reload();
          }, 1500);
        }
      },
      complete: function (res) {
        layer.closeAll("loading");
      },
    });
  });

  //上传头像
  var avatarSrc = $("#LAY_avatarSrc");
  upload.render({
    url: "/admin/index/noOperation",
    elem: "#LAY_avatarUpload",
    auto: true,
    choose: function (obj) {
      layer.load();
      var choosefile;
      obj.preview(function (index, file, result) {
        choosefile = file;
      });
      admin.req({
        url: "/admin/user/signForCos",
        success: function (res) {
          if (res.code == 0) {
            var cos = new COS({
              getAuthorization: function (options, callback) {
                var credentials = res.data.credentials;
                callback({
                  TmpSecretId: credentials.tmpSecretId,
                  TmpSecretKey: credentials.tmpSecretKey,
                  XCosSecurityToken: credentials.sessionToken,
                  ExpiredTime: res.data.expiredTime,
                });
              },
              Domain: res.data.imgDomain,
            });
            cos.putObject(
              {
                Bucket: res.data.bucket,
                Region: res.data.region,
                Key: "images/" + res.data.filename + choosefile.name,
                Body: choosefile,
              },
              function (err, data) {
                console.log(data);
                layer.closeAll("loading");
                if (err) {
                  layer.msg("上传失败", { icon: 5 });
                } else {
                  if (data.statusCode == 200) {
                    avatarSrc.val("https://" + data.Location);
                  } else {
                    layer.msg("图片上传失败", { icon: 5 });
                  }
                }
              }
            );
          } else {
            layer.closeAll("loading");
            layer.msg(res.msg, { icon: 5 });
          }
        },
        error: function () {
          layer.closeAll("loading");
        },
      });
    },
  });

  //查看头像
  admin.events.avartatPreview = function (othis) {
    var src = avatarSrc.val();
    if (src) {
      layer.photos({
        photos: {
          title: "查看头像", //相册标题
          data: [
            {
              src: src, //原图地址
            },
          ],
        },
        shade: 0.01,
        closeBtn: 1,
        anim: 5,
      });
    }
  };

  //上传封面图
  var coverImgSrc = $("#LAY_coverImgSrc");
  upload.render({
    url: "/admin/index/noOperation",
    elem: "#LAY_coverImgUpload",
    auto: true,
    choose: function (obj) {
      layer.load();
      var choosefile;
      obj.preview(function (index, file, result) {
        choosefile = file;
      });
      admin.req({
        url: "/admin/user/signForCos",
        success: function (res) {
          if (res.code == 0) {
            var cos = new COS({
              getAuthorization: function (options, callback) {
                var credentials = res.data.credentials;
                callback({
                  TmpSecretId: credentials.tmpSecretId,
                  TmpSecretKey: credentials.tmpSecretKey,
                  XCosSecurityToken: credentials.sessionToken,
                  ExpiredTime: res.data.expiredTime,
                });
              },
            });
            cos.putObject(
              {
                Bucket: res.data.bucket,
                Region: res.data.region,
                Key: "images/" + res.data.filename + choosefile.name,
                Body: choosefile,
              },
              function (err, data) {
                layer.closeAll("loading");
                if (err) {
                  layer.msg("上传失败", { icon: 5 });
                } else {
                  if (data.statusCode == 200) {
                    coverImgSrc.val("https://" + data.Location);
                  } else {
                    layer.msg("图片上传失败", { icon: 5 });
                  }
                }
              }
            );
          } else {
            layer.closeAll("loading");
            layer.msg(res.msg, { icon: 5 });
          }
        },
      });
    },
  });

  //查看封面图
  admin.events.coverImgPreview = function (othis) {
    var src = coverImgSrc.val();
    if (src) {
      layer.photos({
        photos: {
          title: "查看头像", //相册标题
          data: [
            {
              src: src, //原图地址
            },
          ],
        },
        shade: 0.01,
        closeBtn: 1,
        anim: 5,
      });
    }
  };

  //查看照片
  admin.events.photosPreview = function (othis) {
    let urls = othis.attr("value");
    let urlarr = new Array();
    $.each(urls.split(","), function (i, val) {
      urlarr.push({ src: val });
    });
    layer.photos({
      photos: {
        title: "查看照片", //相册标题
        data: urlarr,
      },
      shade: 0.01,
      closeBtn: 1,
      anim: 5,
    });
  };

  ///////////////////////////////////////////////  report ////////////////////////////////////////////////

  table.render({
    elem: "#LAY-user-report-manage",
    url: "/admin/user/getReportList",
    cols: [
      [
        { field: "id", width: 100, title: "ID", sort: true, fixed: "left" },
        {
          field: "",
          title: "举报用户",
          width: 200,
          templet: function (d) {
            return d.user.nick_name + "(" + d.uid + ")";
          },
        },
        {
          field: "",
          title: "被举报用户",
          width: 200,
          templet: function (d) {
            return d.anchor.nick_name + "(" + d.anchor.id + ")";
          },
        },
        { field: "title", title: "举报理由", width: 200 },
        { field: "content", title: "举报内容", minWidth: 200 },
        {
          field: "",
          title: "图片",
          width: 80,
          templet: function (d) {
            if (d.img_urls && d.img_urls.length > 0) {
              let images = d.img_urls.split(",");
              return (
                '<img style="display: inline-block; width: auto; height: 100%;" src= "' +
                images[0] +
                '" layadmin-event="photosPreview" value="' +
                d.img_urls +
                '">'
              );
            }
            return "";
          },
        },
        {
          title: "操作",
          width: 150,
          align: "center",
          fixed: "right",
          toolbar: "#table-userlist-operation",
        },
      ],
    ],
    page: true,
    limit: 20,
    height: "full-140",
    text: "对不起，加载出现异常！",
    even: true,
  });

  //监听工具条
  table.on("tool(LAY-user-report-manage)", function (obj) {
    if (obj.event === "view") {
      var index = layer.open({
        type: 2,
        title: "短视频",
        content: "/admin/user/edit?id=" + obj.data.userid,
        maxmin: true,
        area: ["600px", "550px"],
      });
      layer.full(index);
    }
  });

  ///////////////////////////////////////////////  room-admin ////////////////////////////////////////////////

  table.render({
    elem: "#LAY-user-room-admin",
    url: "/admin/user/getRoomAminList",
    cols: [
      [
        { field: "id", title: "ID", sort: true, fixed: "left" },
        { field: "mgrid", title: "管理员ID" },
        {
          field: "anchorid",
          title: "主播ID",
          templet: function (d) {
            if (d.anchorid == 0) {
              switch (d.type) {
                case 0:
                  return "<font color='red'>所有主播房间</font>";
                case 1:
                  return "<font color='red'>所有娱乐主播房间</font>";
                case 2:
                  return "<font color='red'>所有体育主播房间</font>";
              }
            } else {
              return d.anchorid;
            }
          },
        },
        { field: "create_time", title: "创建时间" },
        {
          title: "操作",
          align: "center",
          fixed: "right",
          toolbar: "#table-useradmin-operation",
        },
      ],
    ],
    page: true,
    limit: 20,
    height: "full-140",
    text: "对不起，加载出现异常！",
    even: true,
  });

  //监听工具条
  table.on("tool(LAY-user-room-admin)", function (obj) {
    if (obj.event === "setAdmin") {
      layer.confirm("确定取消该用户？", function (index) {
        admin.req({
          url: "/admin/user/setAdmin",
          data: { id: obj.data.mgrid },
          success(res) {
            if (res.code == 0) {
              table.reload("LAY-user-room-admin");
              layer.msg(res.msg, { icon: 1 });
            } else {
              layer.msg(res.msg, { icon: 5 });
            }
          },
        });
      });
    } else if (obj.event == "delRoomManager") {
      layer.confirm("确定解除该房管？", function (index) {
        admin.req({
          url: "/admin/user/delRoomManager",
          data: { id: obj.data.id },
          success(res) {
            if (res.code == 0) {
              table.reload("LAY-user-room-admin");
              layer.msg(res.msg, { icon: 1 });
            } else {
              layer.msg(res.msg, { icon: 5 });
            }
          },
        });
      });
    }
  });

  ///////////////////////////////////////////////  room-banned ////////////////////////////////////////////////
  table.render({
    elem: "#LAY-user-room-banned",
    url: "/admin/user/getBannedList",
    cols: [
      [
        { field: "id", title: "ID", width: 100, sort: true, fixed: "left" },
        { field: "uid", title: "用户ID", fixed: "left" },
        {
          field: "",
          title: "用户昵称",
          templet: function (d) {
            return d.user ? d.user.nick_name : "";
          },
        },
        {
          field: "mgrid",
          title: "管理员",
          templet: function (d) {
            let html = d.manager_name + " &nbsp;&nbsp;";
            switch (d.manager_type) {
              case 1:
                html += '<span class="layui-badge layui-bg-green">房管</span>';
                break;
              case 2:
                html += '<span class="layui-badge layui-bg-red">主播</span>';
                break;
              case 3:
                html +=
                  '<span class="layui-badge layui-bg-blue">后台管理员</span>';
                break;
            }
            return html;
          },
        },
        {
          field: "anchorid",
          title: "禁言房间",
          templet: function (d) {
            if (d.anchorid == 0) {
              return "<font color='red'>所有主播房间</font>";
            } else {
              return d.anchorid;
            }
          },
        },

        { field: "ban_reason", title: "禁言原因" },
        { field: "create_time", title: "创建时间" },
        { field: "ban_time_format", title: "截止时间" },
        {
          title: "操作",
          align: "center",
          fixed: "right",
          toolbar: "#table-userbanned-operation",
        },
      ],
    ],
    page: true,
    limit: 20,
    height: "full-140",
    text: "对不起，加载出现异常！",
    even: true,
  });

  //监听工具条
  table.on("tool(LAY-user-room-banned)", function (obj) {
    if (obj.event === "setBanned") {
      layer.confirm("确定解除禁言？", function (index) {
        admin.req({
          url: "/admin/user/unBanned",
          data: { id: obj.data.id },
          success(res) {
            if (res.code == 0) {
              table.reload("LAY-user-room-banned");
              layer.msg(res.msg, { icon: 1 });
            } else {
              layer.msg(res.msg, { icon: 5 });
            }
          },
        });
      });
    }
  });

  exports("user", {});
});
